package com.simple.demo.socket;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;

public class Server {


    public static void main(String[] args) {
        try {

            ServerSocket server = new ServerSocket();
            SocketAddress address = new InetSocketAddress("localhost", 5000);
            server.bind(address);
            while(true){
                Socket socket = server.accept();
                new Thread(() ->{
                    try {
                        InputStream input = socket.getInputStream();
                        OutputStream output = socket.getOutputStream();
                        int readLen = 0;
                        byte [] readByte = new byte[4];
                        ByteBuffer buffer = ByteBuffer.allocate(100);
                        while((readLen = input.read(readByte)) > 0){
                            buffer.put(readByte,0,readLen);
                        }
                        buffer.flip();
                        System.out.println(new String(buffer.array()));

                        String s ="你好！baimaolin";
                        output.write(s.getBytes());

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                },"oper").start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
